package matchthreegame.handlers;

import matchthreegame.extensions.MatchThreeGameZoneExtension;

import com.smartfoxserver.v2.SmartFoxServer;
import com.smartfoxserver.v2.api.ISFSBuddyApi;
import com.smartfoxserver.v2.api.ISFSGameApi;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.entities.invitation.Invitation;
import com.smartfoxserver.v2.entities.invitation.InvitationCallback;
import com.smartfoxserver.v2.entities.invitation.SFSInvitation;
import com.smartfoxserver.v2.exceptions.SFSBuddyListException;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;

public class InviteUserToBuddylistHandler extends BaseClientRequestHandler {

	MatchThreeGameZoneExtension zoneExtension;

	@Override
	public void handleClientRequest(final User inviterUser, ISFSObject params) {
		// TODO Auto-generated method stub

		SmartFoxServer sfs = SmartFoxServer.getInstance();
		ISFSGameApi gameAPI = sfs.getAPIManager().getGameApi();
		final ISFSBuddyApi buddyApi = sfs.getAPIManager().getBuddyApi();
		zoneExtension = (MatchThreeGameZoneExtension)getParentExtension().getParentZone().getExtension();

		// get names of the Inviter and Invitee
		final String inviterName = inviterUser.getName();
		final String inviteeName = params.getUtfString(zoneExtension.INVITEE_NAME);

		final User inviteeUser = getApi().getUserByName(inviteeName);
		if ( inviteeUser == null ) {
			trace("Invitee = null");
			return;
		}
		// put InvitationType as params
		SFSObject invitationParams = new SFSObject();
		invitationParams.putUtfString(zoneExtension.INVITATION_TYPE, zoneExtension.INVITATION_TYPE_BUDDY);

		// We set the timeout for a reply to 50 seconds 
		Invitation invitation = new SFSInvitation(inviterUser, inviteeUser, 50, invitationParams);

		trace( inviterName + " invited " + inviteeUser.getName());



		// Send the invitation 
		gameAPI.sendInvitation(invitation, new InvitationCallback()
		{
			@Override
			public void onRefused(Invitation invObj, ISFSObject params)
			{
				// Handle the refused invitation
				trace("Invitation was Refused!");
			}

			@Override
			public void onExpired(Invitation invObj)
			{
				// Handle the expired invitation
				trace("Invitation has Expired!");
			}

			@Override
			public void onAccepted(Invitation invObj, ISFSObject params)
			{
				// Handle the accepted invitation
				trace("Invitation was Accepted!");
				try {
					
					// Add both Users as Buddies in their BuddyLists
					buddyApi.addBuddy(inviterUser, inviteeName, false, true, false);
					buddyApi.addBuddy(inviteeUser, inviterName, false, true, false);
					
				} catch (SFSBuddyListException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

	}

}
